package ru.rchervot.sanasar.client.view;

import ru.rchervot.sanasar.client.event.EventQueryChange;
import ru.rchervot.sanasar.client.event.HandlerQueryChange;
import ru.rchervot.sanasar.client.model.Query;
import ru.rchervot.sanasar.client.model.filters.Filter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;

public abstract class AbstractFilterPresenter implements Presenter {

	private final Display display;
	private final HandlerManager eventBus;
	private Query currentQuery;
	
	
	public interface Display extends Presenter.Display {
		public void renderFilter(Filter f);
		public void show();
		public void hide();
		public HasClickHandlers getRemoveFilterButton();
		
		public String getFilterName();
		public String getFilterNameHuman();
	} 
	
	public AbstractFilterPresenter(Display display, HandlerManager eventBus) {
		this.display = display;
		this.eventBus = eventBus;
		
		listenForQueryChange();
	}
	
	protected abstract String getFilterName();
	
	@Override
	public void bindDisplay() {
		display.setPresenter(this);
		
		display.getRemoveFilterButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				currentQuery.removeFilter(getFilterName());
				eventBus.fireEvent(EventQueryChange.build(currentQuery));
			}
		});
	}
	
	protected void listenForQueryChange() {
		eventBus.addHandler(EventQueryChange.getType(),
				new HandlerQueryChange() {
			@Override
			public void onQueryChange(
					EventQueryChange event) {
				currentQuery = event.getQuery();
				
				Filter f = currentQuery.getFilter(getFilterName());
				
				if (f == null) {
					display.hide();
				} else {
					display.renderFilter(f);
					display.show();
				}
			}
		});
	}
}
